package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.dto.pojo.BrandDTO;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 品牌service
 *
 * @author xxx
 */
@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;

    public PageResult<BrandDTO> brandPageQuery(String key, Integer page, Integer rows,
                                               String sortBy, Boolean desc) {
        // 设置分页条件
        PageHelper.startPage(page, rows);
        // 设置封装总对象
        Example example = new Example(Brand.class);
        // 封装查询条件对象
        if (StringUtils.isNotBlank(key)) {
            example.createCriteria()
                    // 模糊查询：WHERE name LIKE '%xxx%'
                    .orLike("name", "%" + key + "%")
                    // toUpperCase() 方法将字符串小写字符转换为大写。
                    // or letter = 'xxx'
                    .orEqualTo("letter", key);
        }
        // 封装排序条件: order by id desc | asc
        example.setOrderByClause(sortBy + " " + (desc ? "DESC" : "ASC"));
        // 分页查询
        List<Brand> brands = brandMapper.selectByExample(example);
        // 判空
        if (CollectionUtils.isEmpty(brands)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        // 得到分页对象
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        // 得到总记录数
        long total = pageInfo.getTotal();
        int totalPage = pageInfo.getPages();
        List<Brand> brandList = pageInfo.getList();
        // 转为PageResult 并返回
        return new PageResult<>(
                total,
                totalPage,
                BeanHelper.copyWithCollection(brandList, BrandDTO.class)
        );
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveBrand(BrandDTO brandDTO, List<Long> cids) {
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
        brand.setId(null);
        int count = brandMapper.insertSelective(brand);
        if (count != 1) {
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        // 新增品牌和分类中间表
        count = brandMapper.insertCategoryBrand(brand.getId(), cids);
        if (count != cids.size()) {
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public BrandDTO queryById(Long brandId) {
        Brand brand = brandMapper.selectByPrimaryKey(brandId);
        if (brand == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand, BrandDTO.class);
    }

    public List<BrandDTO> queryBrandByCategoryId(Long categoryId) {
        List<Brand> brandList = brandMapper.queryByCategoryId(categoryId);
        if (CollectionUtils.isEmpty(brandList)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brandList, BrandDTO.class);

    }

    public List<BrandDTO> queryBrandByIds(List<Long> ids) {
        // 查询分类
        List<Brand> brandList = brandMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(brandList)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        // 转为dto
        return BeanHelper.copyWithCollection(brandList, BrandDTO.class);
    }
}
